package com.ruoyi.system.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.domain.PostComment;
import com.ruoyi.system.domain.vo.PostCommentAuditVo;
import com.ruoyi.system.dto.PostCommentDTO;
import com.ruoyi.system.mapper.PostCommentMapper;
import com.ruoyi.system.service.PostsCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 动态评论业务实现
 */
@Service
public class PostsCommentServiceImpl implements PostsCommentService {
    @Autowired
    private PostCommentMapper commentMapper;

    /** 评论列表 */
    @Override
    public List<PostComment> selectList(PostComment comment) {
        return commentMapper.selectList(comment);
    }

    /** 评论树 */
    @Override
    public List<PostCommentDTO> getCommentTree(Long postId) {
        List<PostComment> list = commentMapper.selectByPostId(postId);
        Map<Long, PostCommentDTO> dtoMap = new HashMap<>();
        List<PostCommentDTO> roots = new ArrayList<>();
        for (PostComment c : list) {
            PostCommentDTO dto = toDto(c);
            dtoMap.put(dto.getId(), dto);
        }
        for (PostComment c : list) {
            PostCommentDTO dto = dtoMap.get(c.getId());
            if (c.getParentId() == null) {
                roots.add(dto);
            } else {
                PostCommentDTO parent = dtoMap.get(c.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) parent.setChildren(new ArrayList<>());
                    parent.getChildren().add(dto);
                } else {
                    roots.add(dto);
                }
            }
        }
        return roots;
    }

    /** 审核评论 */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int audit(PostCommentAuditVo vo) {
        PostComment c = commentMapper.selectById(vo.getId());
        if (c == null) throw new ServiceException("评论不存在");
        return commentMapper.update(c);
    }

    /** 删除评论 */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteById(Long id) {
        return commentMapper.deleteById(id);
    }

    /** 批量删除 */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByIds(Long[] ids) {
        if (ids == null || ids.length == 0) return 0;
        return commentMapper.deleteByIds(ids);
    }

    /** 实体转DTO */
    private PostCommentDTO toDto(PostComment c) {
        PostCommentDTO dto = new PostCommentDTO();
        dto.setId(c.getId());
        dto.setPostId(c.getPostId());
        dto.setUserId(c.getUserId());
        dto.setContent(c.getContent());
        dto.setCreateAt(c.getCreatedAt());
        dto.setParentId(c.getParentId());
        return dto;
    }
}
